package application.common.cron4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.cron4j.ITask;
import application.common.model.StoreBoxLog;
import application.common.render.HttpClientResult;
import application.common.util.HttpUtil;
import application.common.util.ShiroUtil;
import net.sf.json.JSONObject;

/**
 * 存储同步
 * @author love
 *
 */
public class StoreBoxLogTask implements ITask{
	
	private boolean isEnd=true;
	public void run() {
		if(isEnd) {
			isEnd=false;
			if(ShiroUtil.getConfig()!=null && !StrKit.isBlank(ShiroUtil.getConfig().getSynURL())) {
				try {
					
					int pageNumber=1;
					int pageSize=10;
					
					while(true) {
						String sqlExceptSelect = " FROM "+StoreBoxLog.TABLE_NAME+" ";
						Page<StoreBoxLog> pages=StoreBoxLog.dao.paginate(pageNumber, pageSize,"select * " ,sqlExceptSelect);
						if(pages==null || pageNumber>pages.getTotalPage()) {
							break;
						}
						pageNumber++;
						List<StoreBoxLog> stores=pages.getList();
						if(stores!=null && stores.size()>0) {
							Map<String, String> params =new HashMap<String,String>();
							params.put("rows", JsonKit.toJson(stores));
							params.put("cabinetId", ShiroUtil.getAuth());
							HttpClientResult httpClientResult=HttpUtil.doPost(String.format("%s/api/cab/store/saveBoxLogs", ShiroUtil.getConfig().getSynURL()), params);
							if(httpClientResult==null) {
								break;
							}
							if(httpClientResult.getCode()!=200) {
								break;
							}
							String content=httpClientResult.getContent();
							if(StrKit.isBlank(content)) {
								break;
							}
							JSONObject jsonObject=JSONObject.fromObject(content);
							if(jsonObject==null) {
								break;
							}
							if(jsonObject.has("code")) {
								int code=jsonObject.getInt("code");
								if(code!=200) {
									break;
								}
								for(StoreBoxLog storeBoxLog:stores) {
									storeBoxLog.delete();
								}
							}else {
								break;
							}
						}else {
							break;
						}
					}
					isEnd=true;
				}catch (Exception e) {
					isEnd=true;
				}
			}
			isEnd=true;
		}
	}

	public void stop() {
	}

}
